# if PLATFORM is defined then include platform-specific definitions
ifdef PLATFORM
  include $(PLATFORM).mk
else
  # Otherwise use host OS name
  HOST_OS = $(shell uname -o)
  ifeq ($(HOST_OS), GNU/Linux)
    PLATFORM=linux
    SYSLIBS=
  else ifeq ($(HOST_OS), Cygwin)
    PLATFORM=cygwin
    CC=gcc
    EXE=.exe
    SYSLIBS=
  else ifeq ($(HOST_OS), Msys)
    PLATFORM=mingw
    CC=gcc
    EXE=.exe
    SYSLIBS=
  else
    $(error Unknown host OS '$(HOST_OS)')
  endif
endif

# Application program name
NAME = mididump

# Build directory
BUILD_DIR = build/$(PLATFORM)

# uC-MIDI library directory
UCMIDI_DIR = ../../ucmidi

# Application binary (build target)
BINARY = $(BUILD_DIR)/$(NAME)$(EXE)

# Application modules
OBJS = $(addprefix $(BUILD_DIR)/,\
 mididump.o\
 ucmidi.o\
)

# Application libraries
LIBS = $(SYSLIBS)

# C flags
CFLAGS +=\
 -Wall\
 -I.\
 -I$(UCMIDI_DIR)

ifdef DEBUG
CFLAGS += -O0 -g
else
CFLAGS += -O2
endif

# This is to find uC-MIDI library source file.
VPATH = $(UCMIDI_DIR)

#---------------------------------------------------------------------------
# Pattern rules
#---------------------------------------------------------------------------

# Pattern rule to compile C modules
$(BUILD_DIR)/%.o: %.c
	$(CC) $(CFLAGS) -c -o $@ $<

#---------------------------------------------------------------------------
# Buid goals
#---------------------------------------------------------------------------

.PHONY: all pre clean env

# Default build goal (must be first!)
all: pre $(BINARY)

# Prepare for the build
pre:
	@echo Building $(NAME) for $(PLATFORM) platform
	@[ -d $(BUILD_DIR) ] || mkdir -p $(BUILD_DIR)

# Builds mididump application
$(BINARY): $(OBJS)
	$(CC) -o $@ $(LDFLAGS) $^ $(LIBS)

# Delete all files generated bu the build
clean:
	-@$(RM) -r $(BUILD_DIR)/*

# Show build environment (for debugging only)
env:
	@echo PLATFORM=$(PLATFORM)
	@echo UCMIDI_DIR=$(UCMIDI_DIR)
	@echo BINARY=$(BINARY)
	@echo CFLAGS=$(CFLAGS)
	@echo LDFLAGS=$(LDFLAGS)
